package com.zhq.blog.manage.domain.fronted.controller.support;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zhq.blog.core.domain.support.EnumAwareConvertUtilsBean;
import com.zhq.blog.core.domain.user.User;
import com.zhq.blog.manage.domain.fronted.controller.BaseController;
import com.zhq.blog.manage.domain.fronted.controller.SessionUser;

/**
 * @title:UserInterceptor.java
 * @package com.zhq.blog.manage.domain.fronted.controller.support
 * @author 张恒强
 * @date 2015年1月5日 上午10:00:03
 * @version V1.0
 */
public class UserInterceptor extends HandlerInterceptorAdapter {
	protected Log logger = LogFactory.getLog(this.getClass());

	public static final String SESSION_ID_FLAG = "luna_session_id";
	public static final String LOGIN_URL = "/login";
	public static final String LOGIN_VALID_URL = "/login/valid";
	public static final String USER_CENTER = "/usercenter";
	public static final String GAME_CENTER = "/game/play";
	public static final int SESSION_TIMEOUT = -1;
	public static final int SESSION_AUTO_TIMEOUT = 60 * 60 * 24 * 14;
//	@Autowired
//	private SessionUser sessionService;
	
	/**
	 * 因为前台用户多，不再继续使用controller里面放入sessionUser和currentUser
	 * 直接将当前用户放入当前回话session中
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		BeanUtilsBean.setInstance(new BeanUtilsBean(
				new EnumAwareConvertUtilsBean()));
		if ((handler instanceof HandlerMethod && ((HandlerMethod)handler).getBean() instanceof BaseController ) || handler instanceof BaseController) {
			//session最大时间30分钟
			request.getSession().setMaxInactiveInterval(60*30);
			Object  user = request.getSession().getAttribute(SESSION_ID_FLAG);
			if (request.getRequestURI().startsWith(LOGIN_URL)
					||request.getRequestURI().startsWith(LOGIN_VALID_URL)) {
			}else if (request.getRequestURI().matches("^/fgame/\\d+/\\w+$")&&
					!request.getRequestURI().matches("^/fgame/\\d+/index$")&&
					!request.getRequestURI().matches("^/fgame/\\d+/help$")) {
				if (user == null) {
					response.sendRedirect(LOGIN_URL);
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@SuppressWarnings("unused")
	private void setValue(Object _controller, SessionUser session,
			User currentUser) {
		if(_controller instanceof BaseController){
			BaseController controller = (BaseController) _controller;
			controller.setSession(session);
			controller.setCurrentUser(currentUser);
		}
	}

	/**
	 * 返回session id，如果第一次访问或异常访问则返回null
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 返回session id，如果第一次访问或异常访问则返回null
	 */
	@SuppressWarnings("unused")
	private String getSessionId(HttpServletRequest request,
			HttpServletResponse response) {
		String sessionId = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(SESSION_ID_FLAG)) {
					sessionId = cookie.getValue();
				}
			}
		}
		return sessionId;
	}

	/**
	 * 设置用户会话cookie 
	 * 这里存在一个问题，用户可以自行修改cookie过期时间。不过由于cookie机制的安全性，一般认为不是大问题。作为未来改进点。
	 * 
	 * @param response
	 * @param sessionId
	 */
	@SuppressWarnings("unused")
	private void setCookie(HttpServletResponse response, String sessionId) {
		Cookie cookie = new Cookie(SESSION_ID_FLAG, sessionId);
		cookie.setPath("/");
		
		cookie.setMaxAge(SESSION_TIMEOUT);
		
		response.addCookie(cookie);
	}
}
